package com.taotao.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.taotao.mapper.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.enums.IsChargeDesc;
import com.taotao.common.enums.OperateType;
import com.taotao.common.pojo.BaseResult;
import com.taotao.common.utils.Constants;
import com.taotao.common.utils.DateUtil;
import com.taotao.common.utils.RedisUtils;
import com.taotao.mapperCust.CommonMapperCust;
import com.taotao.pojo.EyGoods;
import com.taotao.pojo.EyGoodsExample;
import com.taotao.pojo.EyMember;
import com.taotao.pojo.EyMemberExample;
import com.taotao.pojo.EyOfficialAccounts;
import com.taotao.pojo.EyOfficialAccountsExample;
import com.taotao.pojo.EySessionInfo;
import com.taotao.pojo.EySessionInfoExample;
import com.taotao.service.CommonService;
import com.taotao.service.MemberService;
import com.taotao.service.OperateLogService;
import com.taotao.service.ParamService;

@Service
public class MemberServiceImpl implements MemberService {

	private static final Logger logger = LoggerFactory.getLogger(MemberServiceImpl.class);
	
	@Autowired
	EyMemberMapper eyMemberMapper;
	@Autowired
	EyOperateLogMapper eyOperateLogMapper;
	@Autowired
	EyGoodsMapper eyGoodsMapper;
	@Autowired
	EyCollectMapper eyCollectMapper;
	@Autowired
	EySessionInfoMapper eySessionInfoMapper;
	@Autowired
	EyOfficialAccountsMapper eyOfficialAccountsMapper;
	@Autowired
	OperateLogService operateLogService;
	@Autowired
	CommonMapperCust commonMapperCust;
	BaseResult baseResult = new BaseResult();
	@Autowired
	ParamService paramService;
	@Autowired
	CommonService commonService;
	

	@Override
	public Map<String, Object> wxLogin(Map<String, String> map) {
		try {
			Map<String,String> m=new HashMap<>();
			String unionId = map.get("unionId"); 
			String mobile=map.get("mobile");
			String openId = map.get("openId");
			
			String appId = paramService.getParam("appId_xcx");
			
			EyOfficialAccountsExample exampleAccount = new EyOfficialAccountsExample();
			com.taotao.pojo.EyOfficialAccountsExample.Criteria criteriaAccount = exampleAccount.createCriteria();
			criteriaAccount.andUnionIdEqualTo(unionId);
			List<EyOfficialAccounts> accountlist = eyOfficialAccountsMapper.selectByExample(exampleAccount);
			EyOfficialAccounts accounts=null;
			if(accountlist!=null && accountlist.size()>0){
				accounts = accountlist.get(0);
			}
			
			EyMemberExample example = new EyMemberExample();
			com.taotao.pojo.EyMemberExample.Criteria criteria = example.createCriteria();
			if(StringUtils.isNotBlank(unionId)){
				criteria.andUnionIdEqualTo(unionId);
			}else if(StringUtils.isNotBlank(mobile)){
				criteria.andMobileEqualTo(mobile);
			}else{
				criteria.andAppIdEqualTo(appId);
				criteria.andOpenIdEqualTo(openId);
			}
			
			List<EyMember> memberList = eyMemberMapper.selectByExample(example);
			if(memberList!=null && memberList.size()>0){
				EyMember userInfo = memberList.get(0);
				if(StringUtils.isBlank(userInfo.getNickName())){
					userInfo.setNickName(map.get("nickName"));
				}
				userInfo.setCity(map.get("city"));
				userInfo.setProvince(map.get("province"));
				userInfo.setCountry(map.get("country"));
				if(StringUtils.isNotBlank(userInfo.getAvatarUrl())){
					userInfo.setAvatarUrl(map.get("avatarUrl"));
				}
//				userInfo.setMobile(map.get("mobile"));
				eyMemberMapper.updateByPrimaryKey(userInfo);

				//如果设置了自己的头像，则使用自己的头像，
				if(StringUtils.isNotBlank(userInfo.getImageUrl())){
					userInfo.setAvatarUrl(userInfo.getImageUrl());
				}
				m.put("userInfo", JSONObject.toJSONString(userInfo));
				operateLogService.insert(userInfo.getId(), null,null,"登录成功",OperateType.operateType_3.getCode(),"");

				return baseResult.getSuccMap(m);
			}
			
			ObjectMapper objectMapper = new ObjectMapper();
			objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			EyMember member = objectMapper.convertValue(map, EyMember.class);
			
			Integer publishNumAble = Integer.parseInt(paramService.getParam("publish_num_able"));
			member.setPublishNumAble(publishNumAble);
			
			member.setCreateTime(DateUtil.getDateAndTime());
			member.setUpdateTime(DateUtil.getDateAndTime());
			member.setOpenId(openId);
			member.setAppId(appId);
			if(accounts!=null){
				member.setOpenId2(accounts.getOpenId());
			}
			
			eyMemberMapper.insertSelective(member);
			
//			this.updateImportData(member);
			
			if(accounts!=null){
				accounts.setMemberId(member.getId());
				eyOfficialAccountsMapper.updateByPrimaryKey(accounts);
			}
			
			operateLogService.insert(member.getId(), null,null,"登录成功",OperateType.operateType_3.getCode(),""); 

			//如果设置了自己的头像，则使用自己的头像，
			if(StringUtils.isNotBlank(member.getImageUrl())){
				member.setAvatarUrl(member.getImageUrl());
			}
			m.put("userInfo", JSONObject.toJSONString(member));
			return baseResult.getSuccMap(m);
			
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorJsonObj("网络繁忙，请稍后再试");
		}
	}
	
	/**
	 * 修改导入的数据状态
	 * @param member
	 */
	private void updateImportData(EyMember member) {
		String nickName=member.getNickName();
		if(StringUtils.isNotBlank(nickName)){
			EyMemberExample example = new EyMemberExample();
			com.taotao.pojo.EyMemberExample.Criteria criteria = example.createCriteria();
			criteria.andNickNameEqualTo(nickName);
			List<EyMember> list = eyMemberMapper.selectByExample(example);
			if(list!=null && list.size()>0){
				for(EyMember m:list){
					Integer id = m.getId();
					if(id!=member.getId()){
						//更新goods为已售
						EyGoods goods=new EyGoods();
						goods.setStatus("2"); //已售
						EyGoodsExample exampleGoods = new EyGoodsExample();
						com.taotao.pojo.EyGoodsExample.Criteria criteriaGoods = exampleGoods.createCriteria();
						criteriaGoods.andMemberIdEqualTo(id);
						eyGoodsMapper.updateByExampleSelective(goods, exampleGoods);
					}
				}
			}
		}
	}

	@Override
	public Map<String, Object> queryMemberList(Map<String, String> map) {
		try {
			String pageNum =  map.get("pageNum");
			String pageSize = map.get("pageSize");
			Integer num=StringUtils.isBlank(pageNum)?Constants.pageNum:Integer.parseInt(pageNum);
			Integer size=StringUtils.isBlank(pageSize)?Constants.pageSize:Integer.parseInt(pageSize);
			
			PageHelper.startPage(num,size);
			List<Map> list = commonMapperCust.queryMemberList(map);
			for(Map m:list){
				
				String unionId  = String.valueOf(m.get("unionId"));
				Map<String, String> memberSubscribe = commonService.querySubscribe(unionId);
				m.put("memberSubscribe",memberSubscribe);
				
				String createTime  = String.valueOf(m.get("createTime"));
				m.put("createTime", DateUtil.getDateTimeFormatStr(createTime));
			
				String isAdmin  = String.valueOf(m.get("isAdmin"));
				m.put("isAdminDesc", Constants.num_1.equals(isAdmin)?Constants.yes:Constants.no);
				
				String isBlack  = String.valueOf(m.get("isBlack"));
				m.put("isBlackDesc", Constants.num_1.equals(isBlack)?Constants.yes:Constants.no);
				
				String isCharge  = String.valueOf(m.get("isCharge"));
				m.put("isChargeDesc", IsChargeDesc.getValue(isCharge));
			}
			
			PageInfo<Map> pageInfo = new PageInfo<>(list);
	  		return baseResult.getSuccMap(pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorJsonObj("网络繁忙，请稍后再试");
		}
	}
	
	private Map<String, Object> toMap(EyMember m) {
	    Map<String, Object> map = new HashMap<>();
	    map.put("id", m.getId());
	    map.put("unionId", m.getUnionId());
	    return map;
	}
	
	
	@Override
	public Map<String, Object> getMemberById(Map<String, String> map) {
		try {
			String memberId =  map.get("memberId");
			EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
			//如果设置了自己的头像，则使用自己的头像，
			if(StringUtils.isNotBlank(member.getImageUrl())){
				member.setAvatarUrl(member.getImageUrl());
			}
			return baseResult.getSuccMap(member);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorJsonObj("网络繁忙，请稍后再试");
		}
	}
	
	
	
	@Override
	public Map<String, Object> modifyMember(Map<String, String> map){
		try {
			String memberId =  map.get("memberId");
			String avatarUrl =  map.get("avatarUrl");
			String mobile =  map.get("mobile");
			String wechat =  map.get("wechat");
			String nickName =  map.get("nickName");
			
			EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
			
			avatarUrl=StringUtils.isNotBlank(avatarUrl)?avatarUrl:member.getAvatarUrl();
			mobile=StringUtils.isNotBlank(mobile)?mobile:member.getMobile();
			wechat=StringUtils.isNotBlank(wechat)?wechat:member.getWechat();
			nickName=StringUtils.isNotBlank(nickName)?nickName:member.getNickName();
			
			member.setImageUrl(avatarUrl);
			member.setMobile(mobile);
			member.setWechat(wechat);
			member.setNickName(nickName);
			member.setUpdateTime(DateUtil.getDateAndTime());
			eyMemberMapper.updateByPrimaryKeySelective(member);
			
			operateLogService.insert(member.getId(), null,null,OperateType.operateType_22.getDesc(),OperateType.operateType_22.getCode(),""); 
			return baseResult.getSuccMap(member);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorJsonObj("网络繁忙，请稍后再试");
		}
	}
	
	
	@Override
	public Map<String, Object> modifyMember2(Map<String, String> map){
		try {
			String memberId =  map.get("memberId");
			String isBlack = map.get("isBlack");
			String isAdmin = map.get("isAdmin");
			String isCharge = map.get("isCharge");
			String balance = map.get("balance");
			
			EyMember member = eyMemberMapper.selectByPrimaryKey(Integer.parseInt(memberId));
			
			if(!isBlack.equals(member.getIsBlack()) || 
					!isAdmin.equals(member.getIsAdmin()) ||
					!isCharge.equals(member.getIsCharge())){  //权限有修改，用户需要重新登录
				JSONObject msgJson = new JSONObject();
    			msgJson.put("receiver", memberId);
    			msgJson.put("resultCode", "-2");
    			System.out.println("权限有修改，用户需要重新登录  msgJson->"+msgJson);
    			RedisUtils.lpush(Constants.offLineMsg, msgJson.toJSONString());
			}
			
			isBlack=StringUtils.isNotBlank(isBlack)?isBlack:member.getIsBlack();
			isAdmin=StringUtils.isNotBlank(isAdmin)?isAdmin:member.getIsAdmin();
			isCharge=StringUtils.isNotBlank(isCharge)?isCharge:member.getIsCharge();
			balance=StringUtils.isNotBlank(balance)?balance:member.getBalance();
			
			member.setIsBlack(isBlack);
			member.setIsAdmin(isAdmin);
			member.setIsCharge(isCharge);
			member.setBalance(balance);
			
			member.setUpdateTime(DateUtil.getDateAndTime());
			eyMemberMapper.updateByPrimaryKeySelective(member);
			
//			operateLogService.insert(member.getId(), null,null,map.toString(),OperateType.operateType_22.getCode(),""); 
			return baseResult.getSuccMap(member);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorJsonObj("网络繁忙，请稍后再试");
		}
	}

	
	
	@Override
	public Map<String, Object> getOnlineStatus(Map<String, String> map) {
		try {
			String memberId =  map.get("memberId");
			Map<String,Object> returnMap =new HashMap<String,Object>();
			
		   	String socketId=Constants.socketId_prefix+"_"+memberId;
		   	List<String> socketIdList= RedisUtils.lrange(Constants.onLineScoketId);
		   	boolean flag=false;
        	for(String id:socketIdList){
        	   	if(socketId.equals(id)){
        	   		flag=true;
        	   		break;
        	   	}
        	}
        	returnMap.put("onLine", flag);
			return baseResult.getSuccMap(returnMap);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorJsonObj("网络繁忙，请稍后再试");
		}
	}
	

	@Override
	public Map<String, Object> loadMember(Map<String, String> map) {
		try {
			String memberId =  map.get("memberId");
			String sessionKey =  map.get("sessionKey");
			EySessionInfoExample example = new EySessionInfoExample();
			com.taotao.pojo.EySessionInfoExample.Criteria criteria = example.createCriteria();
			criteria.andSessionKeyEqualTo(sessionKey);
			criteria.andSenderEqualTo(Integer.parseInt(memberId));
	  		List<EySessionInfo> list = eySessionInfoMapper.selectByExample(example);
	  		Map<String,Object> returnMap=new HashMap<String,Object>();
	  		if(list!=null && list.size()>0){
	  			EySessionInfo info = list.get(0);
	  			Integer s = info.getSender();
	  			Integer r = info.getReceiver();
	  			EyMember sender = eyMemberMapper.selectByPrimaryKey(s);
	  			EyMember receiver = eyMemberMapper.selectByPrimaryKey(r);
	  			returnMap.put("sender", sender);
	  			returnMap.put("receiver", receiver);
	  			returnMap.put("sessionKey", sessionKey);
	  		}
	  		return baseResult.getSuccMap(returnMap);
		} catch (Exception e) {
			e.printStackTrace();
			return baseResult.getErrorJsonObj("网络繁忙，请稍后再试");
		}
	}
}
